<template>
  <BasicModal
    destroyOnClose
    width="1200px"
    @register="registerModal"
    title="请选择用户"
    @ok="handleSubmit"
    :bodyStyle="{ padding: '2px' }"
  >
    <FormItemRest>
      <a-row :gutter="10">
        <a-col :span="7">
          <a-card :style="{ minHeight: '550px', overflow: 'auto' }" title="部门列表" size="small">
            <ATree
              v-if="treeData.length"
              :defaultExpandAll="true"
              :checkStrictly="false"
              :treeData="treeData"
              :fieldNames="{ key: 'id', title: 'deptName' }"
              @select="treeSelect"
            />
          </a-card>
        </a-col>
        <a-col :span="17">
          <a-card
            :style="{ minHeight: '550px', overflow: 'auto' }"
            :bodyStyle="{ padding: '0px' }"
            title="用户列表"
            size="small"
            class="user-warp"
          >
            <FormItem>
              <BasicTable @register="registerTable" />
            </FormItem>
          </a-card>
        </a-col>
      </a-row>
    </FormItemRest>
  </BasicModal>
</template>
<script lang="ts" setup>
  import { ref, defineProps } from 'vue';
  import {
    BasicModal,
    useModalInner,
    BasicTable,
    useTable,
    BasicColumn,
    FormSchema,
  } from '@mxpio/components';
  import {
    Tree as ATree,
    Row as ARow,
    Col as ACol,
    Card as ACard,
    FormItemRest,
    FormItem,
  } from 'ant-design-vue';
  import { deptList, deptWithinUser } from '../../../api/system/dept';
  import { getUserList } from '../../../api/system/user';
  import { getQueryParams } from '@mxpio/utils/src/criteria';
  import type { Key } from 'ant-design-vue/lib/table/interface';

  defineOptions({ name: 'UserByDeptModal' });

  const props = defineProps({
    multiple: { type: Boolean, default: true },
  });

  const emit = defineEmits(['success', 'register']);
  let treeData = ref([]);
  let deptCode = ref('');

  const [registerModal, { setModalProps, closeModal }] = useModalInner(async () => {
    setModalProps({ confirmLoading: false });
    getDept();
    reload();
  });

  const columns: BasicColumn[] = [
    {
      title: '用户账号',
      dataIndex: 'username',
    },
    {
      title: '用户姓名',
      dataIndex: 'nickname',
    },
  ];

  const searchFormSchema: FormSchema[] = [
    {
      field: 'username',
      label: '用户账号',
      component: 'Input',
      colProps: { span: 8 },
    },
    {
      field: 'nickname',
      label: '用户名称',
      component: 'Input',
      colProps: { span: 8 },
    },
  ];

  const [registerTable, { reload, getSelectRowKeys, getSelectRows, clearSelectedRowKeys }] =
    useTable({
      api: loadData,
      rowKey: 'username',
      fetchSetting: {
        sizeField: 'size',
        listField: 'content',
        totalField: 'totalElements',
      },
      columns,
      rowSelection: { type: props.multiple ? 'checkbox' : 'radio' },
      striped: false,
      formConfig: {
        labelWidth: 120,
        schemas: searchFormSchema,
      },
      useSearchForm: true,
      showTableSetting: false,
      bordered: true,
      // canResize: true,
      pagination: { pageSize: 10 },
      immediate: false,
      scroll: { y: 300 }, // 表格内容区域高度（不含表头和分页）
    });

  // 获取部门树
  async function getDept() {
    const res = await deptList();
    treeData.value = res;
  }

  // 获取用户列表
  function loadData(queryParams) {
    const params = getQueryParams(queryParams, {});
    // 查询部门用户
    if (deptCode.value) {
      return deptWithinUser(deptCode.value, params);
    }
    // 查询所有用户
    return getUserList(params);
  }

  // 选择
  async function handleSubmit() {
    try {
      const usernames: Key[] = getSelectRowKeys();
      const users: any[] = getSelectRows();
      closeModal();
      emit('success', usernames, users);
    } finally {
      setModalProps({ confirmLoading: false });
    }
  }

  // 选择部门
  function treeSelect(selectedKeys) {
    deptCode.value = selectedKeys[0];
    clearSelectedRowKeys();
    reload();
  }
</script>
<style lang="less">
  .user-warp {
    .ant-pagination-options-size-changer {
      width: auto !important;
    }
  }
</style>
